﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using XDL.Framework;

namespace JumpNFight.Simulation
{
    /// <summary>
    /// Represents a tileset (e.g. a set of image tiles)
    /// </summary>
    public class Tileset
    {
        public int Width;
        public int Height;

        /// <summary>
        /// Tileset texture
        /// </summary>
        public Texture2D TilesetTexture;

        /// <summary>
        /// Tiles properties (by tile ID)
        /// </summary>
        Dictionary<int, List<KeyValuePair<string, string>>> m_tileProperties = new Dictionary<int,List<KeyValuePair<string,string>>>();

        /// <summary>
        /// Returns the "type" property for the given tileset tile.
        /// </summary>
        /// <param name="tile">Tile coordinates</param>
        /// <returns>The tile type, if none, null</returns>
        public string GetTileType(Vector2i tile)
        {
            int key = tile.X + tile.Y * Width;
            return GetTileType(key);
        }

        public string GetTileType(int tileId)
        {
            List<KeyValuePair<string, string>> props = null;
            if (m_tileProperties.TryGetValue(tileId, out props))
                return props.Find((m) => m.Key == "type").Value;

            return null;
        }

        public Tileset(ContentReader input)
        {
            Width = input.ReadInt32();
            Height = input.ReadInt32();

            int count = input.ReadInt32();
            for (int i = 0; i < count; i++)
            {
                int key = input.ReadInt32();
                m_tileProperties.Add(
                    key,
                    input.ReadObject<List<KeyValuePair<string, string>>>(new StringStringPairListReader()));
            }
            TilesetTexture = input.ReadExternalReference<Texture2D>();
        }
    }
}
